package controller;

import com.github.pagehelper.PageInfo;
import constant.Constant;
import entity.Course;
import entity.CourseType;
import exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import service.CourseService;
import service.CourseTypeService;
import util.AjaxResult;
import util.CommonUtil;
import util.DateUtil;
import vo.CourseVo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/course")
public class CourseController {
    @Autowired
    CourseService courseService;
    @Autowired
    CourseTypeService cts;
    //返回课程列表


    //查询所有课程
    @RequestMapping("/findCourse.do")
    @ResponseBody
    public AjaxResult findAllCourse(HttpServletRequest req,CourseVo courseVo) {
        AjaxResult result = new AjaxResult(true, "success", null);

        courseVo.setPageNo(Integer.valueOf(req.getParameter("pageNo")));
        courseVo.setAuthor(String.valueOf(req.getParameter("author")));
        courseVo.setCourse_name(String.valueOf(req.getParameter("course_name")));
        courseVo.setStatus(Integer.valueOf(req.getParameter("status")));
        courseVo.setCourse_type_id(Integer.valueOf(req.getParameter("course_type_id")));
        courseVo.setBegin_date(DateUtil.startDate(req.getParameter("begin_date")));
        courseVo.setEnd_date(DateUtil.endDate(req.getParameter("end_date")));

        PageInfo<Course> info = courseService.findAllCourse(courseVo);
        result.setObj(info);
        return result;
    }

    //查询所有课程类别(三级标题)
    @RequestMapping("/findBackCourseType.do")
    @ResponseBody
    public AjaxResult findAllCourseType() {
        List<CourseType> info = cts.findAllCourseType();
        return AjaxResult.isOk("success",info);
    }

    //启用禁用课程的方法
    @RequestMapping("/toggle.do")
    @ResponseBody
    public void toggleStatus(HttpServletRequest req) {
        Integer id = Integer.valueOf(req.getParameter("id"));
        Integer status = Integer.valueOf(req.getParameter("status"));

        courseService.changeToggleStatus(id, status);

    }

    //修改课程前的查询方法
    @RequestMapping("/show.do")
    @ResponseBody
    public AjaxResult findAllCourseB4Modify(HttpServletRequest req) {
        AjaxResult result = new AjaxResult(true, "success", null);
        Integer id = Integer.valueOf(req.getParameter("id"));
        PageInfo<Course> info = courseService.findAllCourseB4Modify(id);
        System.out.println(info);
        result.setObj(info);
        return result;
    }

    //添加课程的方法
    @PostMapping("/addCourse.do")
    @ResponseBody
    public AjaxResult addCourse(MultipartFile multiFiles, Course c, HttpSession session, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String courseName = req.getParameter("course_name");
        String courseTypeId = req.getParameter("course_type_id");
        int  num = courseService.queryNum(courseName, courseTypeId);
        if (num > 0) {
            return AjaxResult.isFail("当前课程已存在！");
        }
//        获取图片上传的路径
        CommonUtil.setContext(session.getServletContext());// 设置上下文
        String uploadPath = CommonUtil.getUploadPath();

        File dirfile = new File(uploadPath, Constant.IMAGE_FILE);
//        资源文件：如果路径不存在，则创建
        if (!dirfile.exists()) {
            dirfile.mkdirs();
        }
//        获取图片名称
        String imagename = multiFiles.getResource().getFilename();

        // 上传图片
        try {
//        访问文件
            File imageFile = new File(dirfile,imagename);
            RandomAccessFile randomAccessFile = new RandomAccessFile(imageFile, "rw");
//        跳转到初始位置
            randomAccessFile.seek(0);
//        写入文件内容
            randomAccessFile.write(multiFiles.getBytes());
            randomAccessFile.close();
        } catch (IOException e) {
            return AjaxResult.isFail("上传失败！");
        }

        c.setCover_image_url(imagename.substring(0,imagename.lastIndexOf(".")));
        c.setCreate_date(new Date());
        c.setClick_number(0);
        c.setStatus(0);

        courseService.addCourse(c);
        return AjaxResult.isOk("已成功添加课程！");
    }

    //修改课程的方法
    @PostMapping("/modifyCourse.do")
    @ResponseBody
    public AjaxResult modifyCourse(MultipartFile multiFiles, Course c, HttpSession session) throws IOException {
        System.out.println("multiFiles="+multiFiles+"Course="+c);
        if (multiFiles == null) {
            return AjaxResult.isFail("请选择文件！");
        }

        // 获取图片上传的路径
        CommonUtil.setContext(session.getServletContext());// 设置上下文
        String uploadPath = CommonUtil.getUploadPath();
        System.out.println("uploadPath="+uploadPath);

        File dirfile = new File(uploadPath, Constant.IMAGE_FILE);
//        资源文件：如果路径不存在，则创建
        if (!dirfile.exists()) {
            dirfile.mkdirs();
        }

//        获取图片名称
        String imagename = multiFiles.getResource().getFilename();

//        上传图片
        try {
//        访问文件
            File imageFile = new File(dirfile,imagename);
            RandomAccessFile randomAccessFile = new RandomAccessFile(imageFile, "rw");
//        跳转到初始位置
            randomAccessFile.seek(0);
//        写入文件内容
            randomAccessFile.write(multiFiles.getBytes());
            randomAccessFile.close();
        } catch (IOException e) {
            return AjaxResult.isFail("上传失败！");
        }

        c.setCover_image_url(imagename);
        courseService.modifyCourse(c);
        System.out.println("okkkkkkkkkkkkkkkkk");
        return AjaxResult.isOk("已成功修改课程！");
    }


    //跳转到章节管理页面
    @RequestMapping("/back_courseReourceSet")
    public String backCourseReourceSet(HttpServletRequest req) {
        req.setAttribute("course_id",req.getParameter("id"));
        return "/background/back_courseReourceSet";//转发
    }



    //加载获取当前课程下点击量前三多的课程
    @RequestMapping("/loadRecCourse1.do")
    @ResponseBody
    public AjaxResult loadRecCourse(HttpServletRequest req, Integer courseid) {
        AjaxResult result = new AjaxResult(true, "加载当前课程下点击量前三多的课程", null);
        if (req.getParameter("course_id") != ""&&req.getParameter("course_id") != "") {
            courseid=Integer.valueOf(req.getParameter("course_id"));
        }else {
//            result.setObj(null);
//            return result;
            courseid =1;
        }
        List<Course> info = courseService.loadRecCourse(courseid);
        result.setObj(info);
        return result;
    }

    /*
前台功能
加载当前课程所在类别下 点击量前三的课程信息
data:{"course_id":course_id}
**/
    @RequestMapping("/loadRecCourse.do")
    @ResponseBody
    public AjaxResult loadRecCourse(Integer course_id){
        AjaxResult result = new AjaxResult(true, "查询成功", null);
//        List<Course> courses = courseService.selectTop3ById(course_id);
        List<Course> courses = courseService.selectTop3ById(2);
        result.setObj(courses);
        return result;
    }
//===========================

    // 加载点击量前十五的数据
    @RequestMapping("/showTop15.do")
    @ResponseBody
    public List<Course> showTop15() {
        List<Course> courses = new ArrayList<>();
        try {
            courses = courseService.findTop15();
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        System.out.println("showTop15.do_size=" + courses.size());
        return courses;
    }

    // 分页查询课程、按时间排序
    @RequestMapping("/findAllCourse.do")
    @ResponseBody
    public PageInfo<Course> findAllCourse(Integer pageNo, Integer course_type_id, HttpSession session) {
        System.out.println("findAllCourse中的pageNo=" + pageNo + ",course_type_id=" + course_type_id);
        PageInfo<Course> info = new PageInfo<>();

        try {
//            表示用户选中的是顶级分类里边的全选按钮，清空session中的对应值
            if (null == course_type_id) {
                session.removeAttribute(Constant.SESSION_DIRECTION);
            }

            Map<Integer, List<CourseType>> direction = (Map<Integer, List<CourseType>>) session.getAttribute(Constant.SESSION_DIRECTION);

            info = courseService.findCourseByCourseTypeId(pageNo, course_type_id, direction);
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        System.out.println("findAllCourse返回info=====");
        System.out.println(info);
        return info;
    }

    //    根据条件分页查询当前课程中的章节
    @RequestMapping("/idHolder.do")
    public void idHolder(Integer id,HttpSession session){
        session.setAttribute(Constant.COURSE_ID,id);
    }

    //    跳转到“我的课程”页面
    @RequestMapping("/findAllCourseForFront.do")
    public String findAllCourseForFront(HttpSession session){
        session.setAttribute("courseList",courseService.findAllCourseForFront());
        return "front/front_mycourse";
    }
}
